package com.stock;

import com.common.Constant;
import com.common.UtilTools;
import com.soecode.wxtools.bean.KeyWord;
import com.soecode.wxtools.bean.TemplateSender;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by lzb on 2018/5/11.
 */
public class StockMsg {
    public static RestTemplate restTemplate=new RestTemplate();
    private static RedisTemplate redisTemplate = (RedisTemplate) Constant.ctx.getBean("redisTemplate");

    static String purl="https://xueqiu.com/v4/stock/quote.json?code=";
    static String cookie=null;

    public static void loginCookie(){
        ResponseEntity entry = restTemplate.getForEntity("https://xueqiu.com/S/25849", String.class);
        List<String> cookies = entry.getHeaders().get("Set-Cookie");
        StringBuilder cookstr = new StringBuilder();
        for (String cookie : cookies) cookstr.append(cookie.split(";")[0]).append(";").append(" ");
//            System.out.println(cookstr.toString());
        cookie=cookstr.toString();
    }


    static ResponseEntity<String> getWlInf(List<String> codes){
        return UtilTools._POST(purl+ StringUtils.join(codes,",")).addHead("Cookie",cookie).exchange_get(new ParameterizedTypeReference<String>() {});

    }


    public static ResponseEntity<String> getCodesJson(List<String> codes){
        if(cookie==null) {
            loginCookie();
        }
        ResponseEntity<String> rp= null;
        try {
            rp = getWlInf(codes);
        } catch (Exception e) {
            cookie=null;
            loginCookie();
            rp = getWlInf(codes);
        }
        return rp;
    }

    /**
     * 美的&格力策略
     * @return
     */
    public static String getMDGE(){

        List<String> codes=Arrays.asList("SZ000333","SZ000651");
        ResponseEntity<String> rp=getCodesJson(codes);
        JSONObject json=JSONObject.fromObject(rp.getBody());

        JSONObject md=json.getJSONObject("SZ000333");//美的
        JSONObject gl=json.getJSONObject("SZ000651");//格力

        BigDecimal mdp=new BigDecimal(md.getString("current"));
        BigDecimal glp=new BigDecimal(gl.getString("current"));
        BigDecimal subabs=mdp.subtract(glp).abs();


        StringBuffer sb=new StringBuffer("美的价格:").append(mdp.toString()).append("\n");
        sb.append("格力价格:").append(glp.toString()).append("\n");
        sb.append("相差:").append(subabs.toString()).append("\n");
        sb.append("美的占比:").append(subabs.divide(mdp,4,BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100)).setScale(2).toString()).append("%\n");
        sb.append("格力占比:").append(subabs.divide(glp,4,BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100)).setScale(2).toString()).append("%\n");

        return sb.toString();
    }

    public static String getPrice(List<String> codes,List<String> buylist){
//        purl="https://xueqiu.com/v4/stock/quote.json?code=";
        StringBuffer sb=new StringBuffer("最新价格:\n");

        ResponseEntity<String> rp=getCodesJson(codes);

        JSONObject json=JSONObject.fromObject(rp.getBody());
        for(String code:codes){
            JSONObject stock=json.getJSONObject(code);
            String name=stock.getString("name");
            String price=stock.getString("current");
            String zf=stock.getString("percentage");
            if(Double.valueOf(zf)>=0)zf="+"+zf;
            if(buylist.contains(code))sb.append("<a href='https://xueqiu.com/S/"+code+"'>");
            sb.append(code).append(" ").append(name).append(" ").append(price).append(" ").append(zf);
            if(buylist.contains(code))sb.append("</a>");
            sb.append("\n");
        }
        return sb.toString();
    }

    public static TemplateSender checkWl(List<String> codes, List<String> buylist){
        TemplateSender sender = new TemplateSender();
        sender.setTouser("oqcqkw8qmuLdS9qzm6p7oVhrIKPc");
        sender.setTemplate_id("vSpfLZof5KkuUoexGG3bpesS--HtbIxW7KGCmmfo_BQ");
        if(cookie==null)loginCookie();
        ResponseEntity<String> rp= null;
        try {
            rp = getWlInf(codes);
        } catch (Exception e) {
            cookie=null;
            loginCookie();
            rp = getWlInf(codes);
        }
        JSONObject json=JSONObject.fromObject(rp.getBody());
        List<JSONObject> sts=new ArrayList<>(codes.size()*2);
        Map<String,JSONObject> smap=new HashMap<>(codes.size()*2);
        for(String code:codes){
            JSONObject stock=json.getJSONObject(code);
            smap.put(code,stock);
            sts.add(stock);
        }
        sts.sort((s1,s2)->Double.valueOf(s1.getString("current")).compareTo(Double.valueOf(s2.getString("current"))));
        if(sts.size()>0 && buylist.size()==1 && !buylist.contains(sts.get(0).getString("code"))){

            JSONObject lowest=sts.get(0);

            KeyWord first=new KeyWord(String.format("当前购买涡轮%s_%s_%s已不是最低价，请立即调仓!\n当前最低价:",buylist.get(0),smap.get(buylist.get(0)).getString("name"),smap.get(buylist.get(0)).getString("current")));

            KeyWord keyword1=new KeyWord(lowest.getString("name"));
            KeyWord keyword2=new KeyWord(lowest.getString("code"));
            KeyWord keyword3=new KeyWord("换仓");
            KeyWord keyword4=new KeyWord(lowest.getString("current"));
            KeyWord keyword5=new KeyWord(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            sender.getData().put("first",first);
            sender.getData().put("keyword1",keyword1);
            sender.getData().put("keyword2",keyword2);
            sender.getData().put("keyword3",keyword3);
            sender.getData().put("keyword4",keyword4);
            sender.getData().put("keyword5",keyword5);


        }else{
            sender=null;
        }
        return sender;
    }

}
